<template>
  <view class="page">
    <!-- 新用户提示 -->
    <view class="new-user-notice" v-if="userLevel === 0">
      <view class="notice-content">
        <view class="notice-icon">
          <text class="iconfont icon-info"></text>
        </view>
        <view class="notice-text">
          <text class="notice-title">完成一单后才能开启</text>
          <text class="notice-subtitle">购买任意商品即可激活您的账户</text>
        </view>
      </view>
    </view>

    <!-- 消费检查提示 -->
    <view class="consumption-notice" v-if="userLevel > 0 && !canInvite">
      <view class="notice-content">
        <view class="notice-icon">
          <text class="iconfont icon-warning"></text>
        </view>
        <view class="notice-text">
          <text class="notice-title">需要完成消费才能邀请</text>
          <text class="notice-subtitle">{{ inviteMessage }}</text>
        </view>
      </view>
    </view>

    <!-- 状态卡片 -->
    <view class="status-card">
      <view class="status-header">
        <text class="status-title">我的等级</text>
        <text class="level-badge" :class="levelClass">{{ levelText }}</text>
      </view>
      <view class="stats-row">
        <view class="stat-item">
          <text class="stat-value">{{ directCount }}</text>
          <text class="stat-label">直推人数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ newUserCount }}</text>
          <text class="stat-label">邀请名单</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ completedConditions }}/{{ totalConditions }}</text>
          <text class="stat-label">升级进度</text>
        </view>
      </view>
    </view>

    <!-- 升级条件 -->
    <view class="upgrade-section" v-if="userLevel == 1">
      <view class="section-title">
        <text class="title-text">升级条件</text>
        <text class="title-subtitle">完成以下条件即可升级为店长</text>
      </view>
      <view class="condition-list">
        <view class="condition-item" v-for="condition in upgradeConditions" :key="condition.id">
          <view class="condition-icon" :class="condition.is_completed ? 'completed' : 'pending'">
            <text class="iconfont" :class="condition.is_completed ? 'icon-check' : 'icon-clock'"></text>
          </view>
          <view class="condition-content">
            <text class="condition-title">{{ getConditionTitle(condition) }}</text>
            <text class="condition-progress">{{ condition.current_count || 0 }}/{{ condition.target_count }}</text>
          </view>
          <view class="condition-status">
            <text class="status-text" :class="condition.is_completed ? 'completed' : 'pending'">
              {{ condition.is_completed ? '已完成' : '进行中' }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 直推团队 -->
    <view class="team-section">
      <view class="section-title">
        <text class="title-text">直推团队</text>
        <text class="title-subtitle">正式团队成员（会员/店长）</text>
      </view>
      <view class="team-list">
        <!-- 我的直接下级（分红线和财富线） -->
        <view v-if="myDirectUsers.length > 0">
          <view class="group-title">
            <text class="group-title-text">我的分红线和财富线</text>
            <text class="group-subtitle">我的直接下级</text>
          </view>
          <view class="team-item" v-for="member in myDirectUsers" :key="member.user_id" v-if="!loading">
            <image class="member-avatar" :src="member.user?.avatar || '/static/images/default_avatar.png'" mode="aspectFill"></image>
            <view class="member-info">
              <view class="member-name">
                {{ member.user?.nickname || '用户' + member.user_id }}
                <text class="level-tag" :class="getLevelClass(member.level)">
                  {{ getLevelText(member.level) }}
                </text>
              </view>
              <view class="member-mobile">{{ member.user?.mobile || '' }}</view>
              <view class="member-time">邀请时间：{{ formatTime(member.create_time) }}</view>
            </view>
            <view class="member-level">
              <text class="level-tag dividend-line" v-if="member.user_type === 1">
                分红线
              </text>
              <text class="level-tag wealth-line" v-if="member.user_type === 2">
                财富线
              </text>
            </view>
          </view>
        </view>
        
        <!-- 分隔线 -->
        <view class="divider" v-if="myDirectUsers.length > 0 && otherDirectUsers.length > 0"></view>
        
        <!-- 其他人的直接下级 -->
        <view v-if="otherDirectUsers.length > 0">
          <view class="group-title">
            <text class="group-title-text">团队分红线和财富线</text>
            <text class="group-subtitle">团队中的其他成员</text>
          </view>
          <view class="team-item" v-for="member in otherDirectUsers" :key="member.user_id" v-if="!loading">
            <image class="member-avatar" :src="member.user?.avatar || '/static/images/default_avatar.png'" mode="aspectFill"></image>
            <view class="member-info">
              <view class="member-name">
                {{ member.user?.nickname || '用户' + member.user_id }}
                <text class="level-tag" :class="getLevelClass(member.level)">
                  {{ getLevelText(member.level) }}
                </text>
              </view>
              <view class="member-mobile">{{ member.user?.mobile || '' }}</view>
              <view class="member-time">加入时间：{{ formatTime(member.create_time) }}</view>
            </view>
            <view class="member-level">
              <text class="level-tag dividend-line" v-if="member.user_type === 1">
                分红线
              </text>
              <text class="level-tag wealth-line" v-if="member.user_type === 2">
                财富线
              </text>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && directTeamList.length === 0">
          <view class="empty-content">
            <text class="empty-title">暂无直推成员</text>
            <text class="empty-subtitle">邀请的用户完成首单后即可成为直推成员</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 邀请名单 -->
    <view class="team-section">
      <view class="section-title">
        <text class="title-text">邀请名单</text>
        <text class="title-subtitle">新用户（不计入直推）</text>
      </view>
      <view class="team-list">
        <!-- 加载状态 -->
        <view class="loading-state" v-if="loading">
          <view class="loading-spinner"></view>
          <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 新用户列表 -->
        <view class="team-item" v-for="member in newUserList" :key="member.user_id" v-else>
          <image class="member-avatar" :src="member.user?.avatar || '/static/img/default_avatar.png'" mode="aspectFill"></image>
          <view class="member-info">
            <view class="member-name">{{ member.user?.nickname || '用户' + member.user_id }}</view>
            <view class="member-mobile">{{ member.user?.mobile || '' }}</view>
            <view class="member-time">邀请时间：{{ formatTime(member.create_time) }}</view>
          </view>
          <view class="member-level">
            <text class="level-tag new-user">
              新用户
            </text>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && newUserList.length === 0">
          <view class="empty-content">
            <text class="empty-title">暂无邀请用户</text>
            <text class="empty-subtitle">快去邀请好友加入吧~</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 邀请按钮已删除 -->
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { getLinkageRelation, getLinkageTeamStats, getLinkageUpgradeConditions, checkCanInvite } from '@/utils/api'

// 数据定义
const userLevel = ref(0) // 0=新用户，1=普通用户，2=店长
const teamStats = ref<any>({})
const upgradeConditions = ref<any[]>([])
const teamList = ref<any[]>([]) // 原始团队数据
const newUserList = ref<any[]>([]) // 新用户列表
const directTeamList = ref<any[]>([]) // 直推团队列表（会员和店长）
const myDirectUsers = ref<any[]>([]) // 我的直接下级（分红线和财富线）
const otherDirectUsers = ref<any[]>([]) // 其他人的直接下级
const loading = ref(false)
const canInvite = ref(false) // 是否可以邀请
const inviteMessage = ref('') // 邀请提示信息

// 计算属性
const levelText = computed(() => {
  return getLevelText(userLevel.value)
})

const levelClass = computed(() => {
  return getLevelClass(userLevel.value)
})

const completedConditions = computed(() => {
  return upgradeConditions.value.filter(item => item.is_completed).length
})

const totalConditions = computed(() => {
  return upgradeConditions.value.length
})

// 计算直推人数（只计算会员和店长）
const directCount = computed(() => {
  return directTeamList.value.length
})

// 计算新用户数量
const newUserCount = computed(() => {
  return newUserList.value.length
})

// 页面加载
onLoad(() => {
  loadData()
})

onPullDownRefresh(() => {
  loadData().finally(() => {
    uni.stopPullDownRefresh()
  })
})

// 加载数据
const loadData = async () => {
  if (loading.value) return
  loading.value = true
  
  try {
    // 并行加载所有数据
    const [relationRes, statsRes, conditionsRes, inviteCheckRes] = await Promise.all([
      getLinkageRelation({}),
      getLinkageTeamStats({}),
      getLinkageUpgradeConditions({}),
      checkCanInvite({})
    ])
    
    // 处理用户等级和关系数据
    if (relationRes.code === 1 && relationRes.data) {
      userLevel.value = relationRes.data.relation?.level || 0
      
        // 处理直推团队（正式成员）
        if (relationRes.data.direct_users && Array.isArray(relationRes.data.direct_users)) {
          const allDirectUsers = relationRes.data.direct_users.map((item: any) => ({
            user_id: item.user_id,
            user: item.user_info || {},
            level: item.level || 1,
            user_type: item.user_type || 0,
            parent_id: item.parent_id || 0,
            create_time: item.create_time
          }))
          
          // 分类处理：按照 parent_id 分组
          const currentUserId = relationRes.data.relation?.user_id || 0
          myDirectUsers.value = []
          otherDirectUsers.value = []
          
          allDirectUsers.forEach((member: any) => {
            if (member.parent_id === currentUserId) {
              // 我的直接下级
              myDirectUsers.value.push(member)
            } else {
              // 其他人的直接下级
              otherDirectUsers.value.push(member)
            }
          })
          
          // 保持原有的 directTeamList 用于统计
          directTeamList.value = allDirectUsers
        }
      
      // 处理邀请名单（新用户）
      if (relationRes.data.new_users && Array.isArray(relationRes.data.new_users)) {
        newUserList.value = relationRes.data.new_users.map((item: any) => ({
          user_id: item.user_id,
          user: item.user_info || {},
          level: item.level || 0,
          create_time: item.create_time
        }))
      }
    }
    
    // 处理团队统计数据
    if (statsRes.code === 1 && statsRes.data) {
      teamStats.value = {
        direct_count: statsRes.data.direct_count || 0,
        team_count: statsRes.data.team_count || 0,
        manager_count: statsRes.data.manager_count || 0
      }
    }
    
    // 处理升级条件数据
    if (conditionsRes.code === 1 && conditionsRes.data) {
      upgradeConditions.value = conditionsRes.data || []
      console.log('升级条件数据:', conditionsRes.data)
    }
    
    // 处理邀请检查结果
    if (inviteCheckRes.code === 1 && inviteCheckRes.data) {
      canInvite.value = inviteCheckRes.data.can_invite || false
      inviteMessage.value = inviteCheckRes.data.message || ''
      console.log('邀请检查结果:', inviteCheckRes.data)
    }
    
    console.log('团队数据加载完成:', {
      userLevel: userLevel.value,
      teamStats: teamStats.value,
      upgradeConditions: upgradeConditions.value,
      teamList: teamList.value,
      newUserList: newUserList.value,
      directTeamList: directTeamList.value,
      myDirectUsers: myDirectUsers.value,
      otherDirectUsers: otherDirectUsers.value,
      directCount: directCount.value,
      newUserCount: newUserCount.value
    })
    
    console.log('升级进度计算:', {
      completed: completedConditions.value,
      total: totalConditions.value,
      conditions: upgradeConditions.value.map(c => ({
        id: c.id,
        title: c.title,
        current_count: c.current_count,
        target_count: c.target_count,
        is_completed: c.is_completed
      }))
    })
    
  } catch (error) {
    console.error('加载团队数据失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 获取条件标题
const getConditionTitle = (condition: any) => {
  return condition.title || '升级条件'
}

// 格式化时间
const formatTime = (timestamp: number) => {
  if (!timestamp) return ''
  const date = new Date(timestamp * 1000)
  return date.toLocaleString('zh-CN')
}

// 获取等级文本
const getLevelText = (level: number) => {
  switch (level) {
    case 0:
      return '新用户'
    case 1:
      return '会员'
    case 2:
      return '店长'
    default:
      return '会员'
  }
}

// 获取等级样式类
const getLevelClass = (level: number) => {
  switch (level) {
    case 0:
      return 'new-user'
    case 1:
      return 'normal'
    case 2:
      return 'manager'
    default:
      return 'normal'
  }
}

// 去邀请页面方法已删除
</script>

<style lang="scss" scoped>
@import './team.scss';
</style>
